225

Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?

Something like the opposite of String#to_i:

"0A".to_i(16) #=>10

Like perhaps:

"0A".hex #=>10

I know how to roll my own, but it's probably more efficient to use a built in Ruby function.

5 Answers 5

354

You can give to_s a base other than 10:

10.to_s(16)  #=> "a"

Note that in ruby 2.4 FixNum and BigNum were unified in the Integer class. If you are using an older ruby check the documentation of FixNum#to_s and BigNum#to_s

Sign up to request clarification or add additional context in comments.

5 Comments

That's the answer I was looking for but it isn't documented on the linked page str.to_s => str is specified as not accepting parameters and has "Returns the receiver." as the only documentation, but it seems to work
sorry about that copy paste mistake of course to_s on string doesn't take arguments but on Fixnum it does :)
Ah, I was looking under Integer for a .to_s method and couldn't find one. I'll look under Fixnum next time as well
Make sure the original number is an instance of Fixnum, Float will throw an exception.
warning - if you're then splitting the hex number into byte-size segments you'll have to check the length of the result, since it won't be padded with a 0
91

How about using %/sprintf:

i = 20
"%x" % i  #=> "14"

7 Comments

Thanks for showing this, I needed something that would get me a fixed length string prepended with '0'. ex: "%02X" % 10 #=> "0A"
And for the other ruby newbies out there: "#%02x%02x%02x" % [255, 0, 10] #=> "#ff000a" - took me a bit to figure out how to send several args.
This is an extremely awesome snippet of Ruby!
@TomD % is a String method that effectively provides a shorthand for sprintf formatting (they make the same internal calls). It's documented in the String class, see ruby-doc.org/core-1.9.3/String.html#method-i-25
Less duplication: [255, 0, 10].map{|x| '%02x'%x}.join
|
83

To summarize:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"

Comments

14

Here's another approach:

sprintf("%02x", 10).upcase

see the documentation for sprintf here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

1 Comment

sprintf("%02X", 10) will be uppercase because of the upper case X. No need for the upcase method to be called. The specific section of the kernel is this: ruby-doc.org/core-1.9.3/Kernel.html#method-i-format
6

Just in case you have a preference for how negative numbers are formatted:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.